<?php
/**
 * Chip class represents an chip 
 */
class Chip extends Model {
	
	public $id;
	public $location_id;
	public $name;
	public $credit; 
	public $super_user;
	public $visited_pages;
	
	/**
	 * constructs parent
	 */
	function __construct() {
		parent::__contruct();
	}

	/** 
	 * Gets an Chip object
	 * @param chip_id The id of the Chip
	 * @return Chip 
	 */		
	function get($chip_id) {	
		$sth = $this->db->prepare('SELECT * FROM chip
								   WHERE id = :chip_id');
		$sth->setFetchMode(PDO::FETCH_INTO, $this);	
		$sth->execute(array(':chip_id' => $chip_id));
		return $sth->fetch();			
	}

	/**  
	 * Gets the current location of the chip
	 * @param chip_id The chip_id of an user
	 * @return Chip with coordinates 
	 */			
	function getMyLocation($chip_id){
		$sth = $this->db->prepare('SELECT l.lat, l.lng FROM chip c INNER JOIN location l ON c.location_id = l.id 
		WHERE c.id = :chip_id');
		$location = new Location();
		$sth->setFetchMode(PDO::FETCH_INTO, $location);
		$sth->execute(array('chip_id' => $chip_id));
		return $sth->fetch();
	}

	/**  
	 * Gets an chip by an account_id 
	 * @param account_id The account_id wich should have the chip
	 * @return Chip 
	 */		
	function getByAccountId($account_id) {
		$sth = $this->db->prepare('SELECT c.* FROM chip c 
								   LEFT JOIN account_chip ac ON ac.chip_id = c.id
								   LEFT JOIN account a ON a.id = ac.account_id								   
								   WHERE a.id = :account_id');
		$sth->execute(array(':account_id' => $account_id));
		return $sth->fetchAll(PDO::FETCH_CLASS, 'Chip');		
	}

	/**  
	 * Save's a Chip object
	 * @return true if saved succesfully else return false 
	 */	
	function save() {
		if($this->id) {
			if($this->db->update('chip', $this)) {
				return true;
			};
		} else {
			if($this->db->insert('chip', $this)) {
				return true;
			};
		}
		return false;
	}
}

/**
 * ChipList represents an chiplist 
 */
class ChipList extends Model {
	
	/**
	 * constructs parent
	 */
	function __construct() {
		parent::__contruct();
	}
	
	/** 
	 * Gets a Chip objectlist
	 * @return Chiplist array
	 */			
	function getByAccountId($account_id) {
		$sth = $this->db->prepare('SELECT c.*, l.* FROM chip c 
								   LEFT JOIN account_chip ac ON ac.chip_id = c.id
								   LEFT JOIN account a ON a.id = ac.account_id		
									LEFT JOIN location l ON l.id = c.location_id						   
								   WHERE a.id = :account_id
								   ORDER BY c.super_user DESC');
		$sth->execute(array(':account_id' => $account_id));
		return $sth->fetchAll(PDO::FETCH_CLASS, 'Chip');		
	}
}